package com.wangzhip.service;

import com.wangzhip.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class IpCountService {

    private Map<String, Integer> ipCountMap = new HashMap<>();

    @Autowired
    private IpProperties ipProperties;

    @Autowired
    //当前的request对象的注入工作由使用当前starter的项目自动装配
    private HttpServletRequest httpServletRequest;
    public void count() {
        //每次掉用当前操作，就记录当前访问IP，然后累计访问次数


        //1.取到当前IP
        String ip = httpServletRequest.getRemoteAddr();
//        System.out.println("----------"+ip);
        //2.根据IP从Map取值，并递增
        Integer orDefault = ipCountMap.getOrDefault(ip, 0);
        ipCountMap.put(ip, orDefault+1);
    }

//    @Scheduled(cron = "0/5 * * * * ?")
    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?")
    public void print(){

        if (ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())) {

            System.out.println("         IP访问监控");
            System.out.println("+-----ip-addr----+---num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.println(String.format("| %18s  |%5d  |",key,value));
            }
            System.out.println("+----------------+--------|");
        }else if (ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())){
            System.out.println("         IP访问监控");
            System.out.println("+-----ip-addr----+");
            for (String key : ipCountMap.keySet()) {
                System.out.println(String.format("| %18s  |",key));
            }
            System.out.println("+----------------+");
        }

        if (ipProperties.getCycleReset()) {
            ipCountMap.clear();
        }
    }
}
